package com.s53.demo.controller;

import com.s53.demo.pojo.User;
import com.s53.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String getAll(Model model) {
        List<User> list = userService.getAll();
        model.addAttribute("userList", list);
        return "user/list";
    }

    @GetMapping("/add")
    public String add() {
        return "user/add";
    }

    @PostMapping
    public String add(User user) {
        userService.add(user);
        return "redirect:/users";
    }

    @GetMapping("/delete")
    public String add(Long id) {
        userService.delete(id);
        return "redirect:/users";
    }

    @GetMapping("/toUpdate")
    public String toUpdate(Long id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user", user);
        return "user/update";
    }

    @PostMapping("/update")
    public String update(User user) {
        userService.update(user);
        return "redirect:/users";
    }
}
